
const gulp = require('gulp')
const ts = require("gulp-typescript");
const tsProject = ts.createProject("tsconfig.build.json");
const less = require('gulp-less')
const replace = require('gulp-replace')
const clean = require('gulp-clean')
const childProcess = require('child_process')

const jsPath = ['src/**/*.{ts,tsx,js}', '!src/_mock.{ts,js)', '!src/examples/**']
const cssPath = ['src/**/*.less','src/**/*.css']
const attrtsPath=['src/**/*.{svg,png,jpg}']

gulp.task('clean', () => {
  return gulp.src(['lib'], { read: false, allowEmpty: true })
    .pipe(clean())
})

gulp.task('js', () => {
  return gulp.src(jsPath, { allowEmpty: true })
    .pipe(tsProject())
    .pipe(replace('.less','.css'))
    .pipe(gulp.dest('lib'))
})

gulp.task('css', () => {
  return gulp.src(cssPath, { allowEmpty: true })
  .pipe(less())
  .pipe(gulp.dest('lib'))
})



gulp.task('attrts', () => {
    return gulp.src(attrtsPath)
      .pipe(gulp.dest('lib'))
  })

gulp.task('watch', () => {
  gulp.watch(jsPath, gulp.series('js'))
  gulp.watch(cssPath, gulp.series('css'))
  gulp.watch(attrtsPath, gulp.series('attrts'))
})

const cmd = (cmdStr) => {
  return new Promise((resolve) => {
    childProcess.exec(cmdStr,{
      maxBuffer: 1024 * 2000
    }, function(err, stdout, stderr) {
        if (err) {
            console.log(err);
        } else if (stderr.lenght > 0) {
            console.error(stderr.join('\n'))
        } else {
            console.log(stdout);
        }

        resolve()
    });
  })
}

gulp.task('yalc:push', cb => {
  cmd('yalc push').then(() => cb())
})

gulp.task('watch:dev', () => {
  gulp.watch(jsPath, gulp.series('js', 'yalc:push'))
  gulp.watch(cssPath, gulp.series('css', 'yalc:push'))
  gulp.watch(attrtsPath, gulp.series('attrts', 'yalc:push'))
})

gulp.task('default', gulp.series('clean', gulp.parallel('watch', 'css', 'js','attrts')))

gulp.task('build', gulp.series('clean', gulp.parallel('css', 'js','attrts')))